// src/stores/system.js
import { defineStore } from 'pinia'
import {
    getSystemInfo,
    updateSystemInfo,
    getApiKeys,
    addApiKey,
    updateApiKey,
    deleteApiKey,
    batchDeleteApiKeys,
    getApiKeyQuota
} from '@/api/system'

export const useSystemStore = defineStore('system', {
    state: () => ({
        systemInfo: {
            systemName: '',
            username: '',
            email: ''
        },
        apiKeys: [],
        total: 0,
        loading: false
    }),

    actions: {
        async getSystemInfo() {
            const res = await getSystemInfo()
            this.systemInfo = res.data
        },

        async updateSystemInfo(data) {
            await updateSystemInfo(data)
            this.systemInfo = { ...this.systemInfo, ...data }
        },

        async getApiKeys(params) {
            this.loading = true
            try {
                const res = await getApiKeys(params)
                this.apiKeys = res.data.records
                this.total = res.data.total
            } finally {
                this.loading = false
            }
        },

        async addApiKey(data) {
            await addApiKey(data)
            await this.getApiKeys({current: 1})
        },

        async updateApiKey(id, data) {
            await updateApiKey(id, data)
            await this.getApiKeys({current: 1})
        },

        async deleteApiKey(id) {
            await deleteApiKey(id)
            await this.getApiKeys({current: 1})
        },

        async batchDeleteApiKeys(ids) {
            await batchDeleteApiKeys(ids)
            await this.getApiKeys({current: 1})
        },

        async getApiKeyQuota(id) {
            const res = await getApiKeyQuota(id)
            return res.data
        }
    }
})